import os,django
import xlrd

os.environ.setdefault ('DJANGO_SETTINGs_MODULE','atl_project.settings')

if django.VERSION >= (1,7):#自动判断版本
    django.setup()

list = []  
def main():
    from atl.models import Category,Atl
    import xlrd
    path = r'c:\users\liangzx3\desktop\django\3.xlsx' 
    data = xlrd.open_workbook (path) # 打开Excel文件读取数据
    table = data.sheets()[0] #通过索引顺序获取
    nrows = table.nrows # 获取行数和 ncols = table.ncols 列数
    
    print ('clean database')
    Atl.objects.all().delete ()
    Category.objects.all ().delete ()
    
    for i in range (1,nrows):
        list.append (table.row_values(i))
        
    for l in list:
        Category.objects.get_or_create (name = l[0])
        cate = Category.objects.get (name = l[0])
        name = l[1]
        link = str(l[2])
        Atl.objects.get_or_create (class_name = cate,name = name,link = link) # 防止导入数据重复  
    
    # Bloglist = []    
    # for ll in list:
        # Bloglist.append (Blog(classs = l[0],name = name [1],link = l[2] ))
   
    # Blog.objects.bulk_create (Bloglist)
    # 由于Blog.objects.create()每保存一条就执行一次SQL，而bulk_create()是执行一条SQL存入多条数据，做会快很多！当然用列表解析代替 for 循环会更快！！
    

if __name__  == '__main__':
    main ()
    print ('Done')
        
        
    
    
